console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { zeroReprot } from './zeroReprot.js';
import { asyncTable } from './asyncTable.js';
import SH from './../commonModule/SH.js';
import { asyncSetInterval, asyncTableDetailStartCQ, getAsyncTableDetailStartStatus } from "../../lib/zeroReportUtils.js";
let baseInfoCache;

$(window).ready(function () {
  window.postMessage(
    {
      event: "getZeroInfo",
    },
    "*"
  );

  let url = [ // 同步报表相关页面
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/cxdy/sbcx.html',
    'https://etax.shenzhen.chinatax.gov.cn/yhs-web/sbbcx/view/sbList.html',
    'https://etax.shenzhen.chinatax.gov.cn/yhs-web/api/sbcx/getSbbmx'
  ];
  let isAsyncTable =  url.some(item => window.location.href.includes(item))
  if (isAsyncTable) {
    getAsyncTableDetailStartStatus();
  }
  // 登录填写账号密码
  if (/\/login-web\/login/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }

  if (/\/byysb\/byysb.html/g.test(window.location.pathname)) {
    $('body').on('click', '.ckjdBtn', function () {
      let $this = $(this),
        $li = $this.closest('.wsdbLi'),
        timeStr = $li.find('.li-title').eq(0).text(),
        taxTypeStr = $li.find('.txt-l').text(),
        taxType = getTaxType(taxTypeStr);

      // 获取申报周期，填充数据
      let period = getReportingCycle(timeStr);

      // 渲染填报时间，填报周期
      sendFilter(period, taxType);
    });
  }

  if (/\/BsfwtWeb\/pages/g.test(window.location.pathname)) {
    $('body').delegate('.mini-tab', 'click', function () {
      var $this = $(this),
        title = $this.find('.mini-tab-text').text(),
        taxType = getTaxType('财务报表', title);

      // 填报周期 渲染
      sendFilter({}, taxType);
    });
  }
});

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    data = data.data;
    let sheet = data.saasData.sheet;
    if (sheet == 'sds' || sheet == 'zzs') {
      fillInput(data, sheet);
    } else {
      fillInput(await transformDataByOpenWeb(data));
    }
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    autoInputAccount(baseInfoCache);
  }

  // 同步申报表
  if (data.event === "getZeroInfoBack") {
    if (data.data.isOpenZeroReport) {
      let loginPage = 'https://etax.shenzhen.chinatax.gov.cn/bszm-web/apps/views/beforeLogin/indexBefore/pageIndex.html';
      let href = window.location.href;
      let { currentZeroInfo } = data.data;
      if(href.includes(loginPage)) { // 关闭引导填充登录信息
        asyncSetInterval(()=>{
          $('#hjjc_win .mini-tools .mini-tools-close ').click();
          $('.qrcode-box .bottom .button').click();
          $('.menu-login .login-btn').click();
          setTimeout(() => {
            $('#app .user-login .wrap:nth-child(1)').css('margin-bottom', '30px').append(`<div>${currentZeroInfo.nationalTaxNo}<div>`);
            $('#app .user-login .wrap:nth-child(2)').css('margin-bottom', '30px').append(`<div>${currentZeroInfo.nationalTaxPass}<div>`);
          }, 200)
          return true;
        },500)
      } else {
        zeroReprot(currentZeroInfo);
      } 
    }
  }

  // 零申报结束返回事件
  if (data.event === 'zeroReportEnd') {
    asyncTableDetailStartCQ(); // 开启同步报表
    setTimeout(()=>{
      window.location.href = 'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/cxdy/sbcx.html?zeroReportEnd=1'; // 返回申报查询页面做同步报表操作 zeroReportEnd=1 表示已同步过申报表
    },1000)
  }

  // 同步报表相关操作
  if (data.event === 'getAsyncTableDetailStartStatusBack') {
    if (data.data.isStart) {
      asyncTable(data.data)
    }
  }

  // 同步报表结束，清除当前信息退出登录
  if (data.event === 'asyncTableDetailRequestEnd') {
    console.log('asyncTableDetailRequestEnd')
    asyncSetInterval(()=>{
      window.postMessage({
        event: "clearZeroReport",
      },
      "*")
      return true;
    },500).then(()=>{
      setTimeout(() => {
        $('#login-out').click();
      }, 1000);
    })
  }

}, false);
/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: getGsInstitution() === 'small' ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: ''// 税款所属期止
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  $('#userName, #shCode').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  $('#passWord, #passWord0').val(companyInfo.nationalTaxPass);
}

function fillInput({ saasData, baseInfo }) {
  const {
    lastYearData, isYearReport, sheetType, sheet
  } = saasData;
  let iframeWindow;
  if (sheetType === 'cwbb') {
    iframeWindow = window;
  } else {
    iframeWindow = $('iframe:visible')[0].contentWindow;
  }

  let message = '填报成功';
  try {
    let inputData = saasData.data;
    if (sheet === 'sds') {
      inputData = delSdsData(inputData.openParams.inputData.data.profit, baseInfo.companyInfo.institutionCode);
    }

    if (isYearReport) {
      inputData = SH.hackYearReportInput(inputData, lastYearData, sheet);
    }

    for (let key in inputData) {
      let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
      if (iframeWindow.$(`input#${key}`).length != 0) {
        iframeWindow.$(`input#${key}`).val(value).trigger('blur');
      }
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}

let getGsInstitution = function () {
  let gsInstitution = 'small';
  let hdxxData = window.window.sessionStorage.getItem('hdxxData');
  hdxxData = JSON.parse(hdxxData) || {};
  let sbzlxx = hdxxData.sbzlxx || [];
  let findItem = sbzlxx.find((item) => {
    return item.SBZLMC.search('财务报表') != -1;
  });

  if (findItem) {
    let SBZLMC = findItem.SBZLMC;
    if (SBZLMC.trim().search('一般企业财务报表') != -1) {
      gsInstitution = 'gener';
    } else if (SBZLMC.trim().search('小企业财务表报') != -1) {
      gsInstitution = 'small';
    }
  }
  return gsInstitution;
};

function delSdsData(tableData, institutionCode) {
  let sdsData = {};
  if (institutionCode == 1) {
    sdsData = {
      '001_8_5': tableData.SQJE_1_1,
      '001_9_5': tableData.SQJE_1_2,
      '001_10_5': tableData.SQJE_1_15
    };
  } else {
    sdsData = {
      '001_8_5': tableData.BNLJJE_1,
      '001_9_5': tableData.BNLJJE_2,
      '001_10_5': tableData.BNLJJE_30
    };
  }

  return sdsData;
}


/**
 * 获取 税类型 用于填充填报类型 '增值税一般纳税人'
 * @returns {taxType}
 */
function getTaxType(taxTypeStr, title) {
  taxTypeStr = taxTypeStr || '增值税一般纳税人';
  let taxType = null;

  if (!title) {
    if (taxTypeStr.search('增值税') != -1) {
      taxType = 'zzs';
    } else if (taxTypeStr.search('所得税') != -1) {
      taxType = 'sds';
    } else if (taxTypeStr.search('财务报表') != -1) {
      taxType = 'balance';
    }
  } else if (title.search('资产负债表') != -1) {
    taxType = 'balance';
  } else if (title.search('利润表') != -1) {
    taxType = 'profit';
  } else if (title.search('现金流量表') != -1) {
    taxType = 'cash';
  } else {
    taxType = 'balance';
  }
  return taxType;
}

/**
 * @param timeStr 时间字符串 2017-04-01~2017-06-30
 * 获取申报周期并且填充数据
 */
function getReportingCycle(timeStr) {
  timeStr = timeStr || '~';
  timeStr = timeStr.split('~');
  let sssq_q = timeStr[0].substr(0, 7);
  let sssq_z = timeStr[1].substr(0, 7);

  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z
  };
}


function sendFilter(period, taxType) {
  let sssq_q = period.sssq_q,
    sssq_z = period.sssq_z;

  if (sssq_q && sssq_z) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType,
        startTime: sssq_q,
        endTime: sssq_z
      }
    }, '*');
  } else if (taxType) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType
      }
    }, '*');
  }
}
